package com.meiya.hugegraph.example;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.hugegraph.driver.HugeClient;
import org.apache.hugegraph.structure.constant.Direction;
import org.apache.hugegraph.structure.graph.Edge;
import org.apache.hugegraph.structure.graph.Vertex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.meiya.hugegraph.api.HugeGraphClientFactory;
import com.meiya.hugegraph.api.HugeGraphManager;
import com.meiya.hugegraph.config.HugeGraphConfig;
import com.meiya.hugegraph.schema.TransactionSchema;
import com.meiya.hugegraph.service.TransactionOperations;

/**
 * 交易图数据操作示例
 * 演示如何使用封装的API进行交易数据的图操作
 */
public class TransactionGraphExample {

    private static final Logger logger = LoggerFactory.getLogger(TransactionGraphExample.class);

    public static void main(String[] args) {
        HugeClient client = null;

        try {
            // 1. 创建HugeClient
            client = HugeGraphClientFactory.createClient();

            // 2. 创建Schema（如果需要）
            // 注释掉下面一行如果Schema已存在
            // createSchema();

            // 3. 创建图管理器
            HugeGraphConfig config = new HugeGraphConfig();
            config.setServerUrl("http://localhost:8080");
            config.setGraphName("hugegraph");
            config.setTimeout(60);
            HugeGraphManager graphManager = new HugeGraphManager(config);
            TransactionOperations transOps = new TransactionOperations(graphManager, config);

            // // 4. 创建银行卡顶点
            Vertex card1 = transOps.createCardVertex("6225123456789001", "张三");
            Vertex card2 = transOps.createCardVertex("6225123456789002", "李四");
            Vertex card3 = transOps.createCardVertex("6225123456789003", "王五");

            logger.info("==== 创建了 3 张银行卡 ====");
            logger.info("卡1: {}", card1);
            logger.info("卡2: {}", card2);
            logger.info("卡3: {}", card3);

            // 5. 创建交易边
            // 张三 -> 李四: 转账1000元
            Edge trans1 = transOps.createTransactionEdge(
                    card1.id(),
                    card2.id(),
                    1000.0,
                    new Date(),
                    generateUkey());

            // 李四 -> 王五: 转账500元
            Edge trans2 = transOps.createTransactionEdge(
                    card2.id(),
                    card3.id(),
                    500.0,
                    new Date(),
                    generateUkey());

            // 王五 -> 张三: 转账200元
            Edge trans3 = transOps.createTransactionEdge(
                    card3.id(),
                    card1.id(),
                    200.0,
                    new Date(),
                    generateUkey());

            logger.info("==== 创建了 3 笔交易 ====");
            logger.info("交易1: {}", trans1);
            logger.info("交易2: {}", trans2);
            logger.info("交易3: {}", trans3);

            // 6. 查询操作
            // 查询持卡人为"张三"的卡
            Map<String, Object> properties = new HashMap<>();
            properties.put("holderName", "张三");
            List<Vertex> zhangSanCards = transOps.getCardsByHolder("张三", 10);

            logger.info("==== 查询张三的卡 ====");
            for (Vertex card : zhangSanCards) {
                logger.info("卡: {}", card);
            }

            // 查询张三卡的所有交易（出/入）
            if (!zhangSanCards.isEmpty()) {
                Vertex zhangSanCard = zhangSanCards.get(0);
                List<String> labels = new ArrayList<>();
                labels.add("transaction");
                List<Edge> transactions = transOps.getTransactionsOfVertex(
                        zhangSanCard.id(), Direction.BOTH, labels, 0);

                logger.info("==== 查询张三卡的所有交易 ====");
                for (Edge transaction : transactions) {
                    String direction = transaction.sourceId().equals(zhangSanCard.id()) ? "转出" : "转入";
                    logger.info("交易{}: {}", direction, transaction);
                }
            }

            // 查询金额大于等于500的交易
            List<Edge> largeTransactions = transOps.getTransactionsAboveAmount(500.0, 10);

            logger.info("==== 查询金额大于等于500的交易 ====");
            for (Edge transaction : largeTransactions) {
                logger.info("大额交易: {}", transaction);
            }

            // 7. 删除操作示例（通常不建议在生产环境执行）
            // 仅用于示例，注释掉防止误删
            /*
             * logger.info("==== 删除操作示例（已注释） ====");
             * // 删除一笔交易
             * // graphManager.removeEdge(trans3.id().toString());
             * 
             * // 删除一张卡
             * // graphManager.removeVertex(card3.id());
             */

        } catch (Exception e) {
            logger.error("示例执行出错", e);
        } finally {
            // 关闭client
            HugeGraphClientFactory.closeClient(client);
        }
    }

    /**
     * 创建Schema
     */
    private static void createSchema() {
        String[] args = new String[0];
        TransactionSchema.main(args);
    }

    /**
     * 生成交易唯一标识
     */
    private static String generateUkey() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        return sdf.format(new Date()) + "-" + UUID.randomUUID().toString().substring(0, 8);
    }
}